package com.kstech.mp3604.base

import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import androidx.activity.viewModels
import androidx.navigation.findNavController
import com.blankii.androidlibrary.base.BaseBindingActivity
import com.blankii.androidlibrary.exts.logd
import com.blankii.androidlibrary.exts.loge
import com.blankii.androidlibrary.utils.ViewClickContinuousUtil
import com.blankii.androidlibrary.utils.ViewClickContinuousUtil.ClickContinuousCallback
import com.blankj.utilcode.util.SPUtils
import com.kstech.mp3604.R
import com.kstech.mp3604.base.Global.APP_AUTOHY_VALUE
import com.kstech.mp3604.base.Global.SETTING_IP
import com.kstech.mp3604.base.Global.SETTING_PORT
import com.kstech.mp3604.base.Global.initConfigParam
import com.kstech.mp3604.data.DbManager
import com.kstech.mp3604.databinding.ActivityMainBinding
import com.kstech.mp3604.fragments.DialogConfirmCancelViewShanFragment
import com.kstech.mp3604.manager.SoundManager
import com.kstech.mp3604.manager.serialComm.SerialCommStatusListener
import com.kstech.mp3604.manager.serialComm.SerialManager
import com.kstech.mp3604.manager.socket.SocketManager
import com.kstech.mp3604.manager.socket.SocketStatusListener
import com.kstech.mp3604.ui.listener.AutoHYListener
import com.kstech.mp3604.ui.listener.DialogConfirmCancelViewShanListener
import com.kstech.mp3604.ui.listener.DialogIpPortListener
import com.kstech.mp3604.ui.listener.LoginSetParamListener
import com.kstech.mp3604.utils.TimeUtil
import com.kstech.xz3604.ui.ViewShanManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * 程序开机自启动 使用场景可能基本不会登出
 */
class MainActivity : BaseBindingActivity<ActivityMainBinding>(ActivityMainBinding::inflate, true),
    SocketStatusListener, LoginSetParamListener, SerialCommStatusListener, DialogIpPortListener,
    DialogConfirmCancelViewShanListener, AutoHYListener {
    private var isHome: Boolean = true
    private val mViewModel: HomeViewModel by viewModels()

    /**
     * 故障灯闪烁逻辑
     * 初始化状态时
     * 正常：绿灯
     * 收到故障：红灯闪烁
     * 点击故障灯：可五分钟之内不再闪烁
     */
    private var closeFaultViewShan = false//
    private var closeFaultViewShanCount = 0 //三分钟计时

    override fun onInitView() {

        mViewModel.loginSetParamListener = this
        mViewModel.ipPortSettingListener = this
        mViewModel.autoHYListener = this


        //设置屏幕常亮
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        //连接tcpSocket
        var ipSetting = SPUtils.getInstance().getString(SETTING_IP)
        if (ipSetting.isNullOrEmpty()) {
            ipSetting = "192.168.1.21"
            SPUtils.getInstance().put(SETTING_IP, ipSetting)
        }
        var portSetting = SPUtils.getInstance().getInt(SETTING_PORT)
        if (portSetting == -1) {
            portSetting = 9006
            SPUtils.getInstance().put(SETTING_PORT, portSetting)
        }
        //todo 动态修改ip 端口在onDestroy 无法把失败连接的缓存清理掉
        SocketManager.initEasySocket(mViewModel, this, this, ipSetting, portSetting)
        //连接串口
        SerialManager.openSerial(mViewModel, this, this)
        //实时刷新时间
        startTimer()
        //绑定标题  连点两下
        ViewClickContinuousUtil.setViewConfig(
            binding.titleText, 2, 2, object : ClickContinuousCallback {
                override fun currentCount(count: Int) {
                }

                override fun success() {
//                    findNavController(R.id.fragment_container_view_act).navigate(R.id.action_dmFragment_to_historyErrorFragment)
                }
            })
        //更新时间戳时间
        //点击故障灯,如果处于闪烁状态的话，可以三分钟内不受故障 闪烁  如果没有闪烁不影响
        binding.faultView.setOnClickListener {
            if (ViewShanManager.isShan(binding.faultView)) {
                DialogConfirmCancelViewShanFragment(this).show(supportFragmentManager)

            }
        }

        mViewModel.isTasking.observe(this) { result ->
            if (result) {
                binding.initNotifyMsg.visibility = View.VISIBLE
                binding.noTaskMsg.visibility = View.GONE
            } else {
                if (mViewModel.dataInit.value == true) {
                    binding.noTaskMsg.visibility = View.VISIBLE
                    binding.initNotifyMsg.visibility = View.GONE
                }
            }
        }
        binding.initNotifyMsg.visibility = View.VISIBLE
        /**
         * 监控homeView 参数
         */
        mViewModel.serialCommIsConnect.observe(this) { it ->
            if (it) {
                "控制器在线".loge(TAG)
            } else {
                //控制器失去联系
                "控制器掉线".loge(TAG)
                mViewModel.device_state.value = Global.RunningStatus.STANDBY
            }
        }
        mViewModel.bothDevicesOnline.observe(this) { bothOnline ->
            if (bothOnline) {
                binding.faultView.setImageResource(R.drawable.commstatus_normal)
                binding.faultView.visibility = View.VISIBLE
            } else {
                binding.faultView.setImageResource(R.drawable.commstatus_warn)
                binding.faultView.visibility = View.VISIBLE
            }

        }
//        mViewModel.networkError.observe(this) { error ->
//            if (error) {
//
//            }
//        }

        val autoHy = SPUtils.getInstance().getInt(APP_AUTOHY_VALUE)
        if (autoHy != -1) {
            Global.app_autoHY_value = autoHy
        }
//        mViewModel.device_state.observe(this) { state ->
//            "state:${state.data}".logd("socket-心跳")
//        }

    }

    //软件开机自启动，很大概率不会登出软件
    override fun onResume() {
        super.onResume()
        SerialManager.onResume()
        SocketManager.onResume()
        //检查数据库的数量是否达条到清理状态，暂时达到300条数据的时候，清理到100
        checkSQLData()
        closeFaultViewShan = false
    }

    override fun onPause() {
        super.onPause()
        SerialManager.onPause()
        SocketManager.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        /**
         * 退回到后台销毁不执行onDestroy
         */
        SocketManager.close()
        SoundManager.close()
        SerialManager.onDestroy()

        TimeUtil.onClear()
    }


    private fun checkSQLData() {
        CoroutineScope(Dispatchers.IO).launch {
            //检查任务表数据量是否溢出
            DbManager.db.taskDataDao().checkData()
            //检查故障表数据量是否溢出
            DbManager.db.errorInfoDao().checkData()
            //检查操作日志数据量是否溢出
            DbManager.db.logDao().checkData()
        }
    }

    private fun startTimer() {
        CoroutineScope(Dispatchers.IO).launch {
            while (true) {
                withContext(Dispatchers.Main) {
                    binding.time.text = TimeUtil.getDateTimeStr()
                }
                delay(1000)

                //判断点击闪烁灯，可以持续多长时间
                if (closeFaultViewShanCount > 5 * 60 && closeFaultViewShan) {
                    closeFaultViewShan = false
                    "人为干预故障灯结束，恢复故障灯正常闪烁".logd(TAG)
                } else {
                    closeFaultViewShanCount++
                }
            }
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (isHome && keyCode == KeyEvent.KEYCODE_BACK) {
            ViewClickContinuousUtil.backClickConfig(object :
                ViewClickContinuousUtil.BackClickCallback {
                override fun success() {
                    finish()
                }

                override fun clickOne() {
                    showSnackBar("再按一次返回键退出")
                }
            })
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onInitData() {
        initConfigParam()
    }


    override fun success() {
//        mViewModel.socketCommIsConnect.value = true
    }

    override fun fail() {
//        mViewModel.socketCommIsConnect.value = false
    }

    override fun disConnect() {
//        mViewModel.socketCommIsConnect.value = false
    }

    override fun gsonFail(e: String) {
        showSnackBar("接收到socket数据，但因数据格式问题解析失败:${e}")
    }

    override fun loginSuccess() {
        "密码成功,请重新输入".loge(TAG)
        val navController = this@MainActivity.findNavController(R.id.fragment_container_view_act)
        navController.navigate(R.id.action_dmFragment_to_setParamFragment)
    }

    override fun loginFail() {
        showSnackBar("密码错误,请重新输入")
    }

    /**
     * 串口连接成功
     */
    override fun isConnect() {
        mViewModel.serialCommIsConnect.postValue(true)
    }

    /**
     * 串口连接失败
     */
    override fun isUnConnect() {
        mViewModel.serialCommIsConnect.postValue(false)
    }

    /**
     * 串口故障闪烁
     */
    override fun serialFaultState(fault: Int) {
        if (closeFaultViewShan) {
            return
        }
        when (fault) {
            0 -> {
                ViewShanManager.close(binding.faultView)
            }

            1 -> {
                binding.faultView.setImageResource(R.drawable.commstatus_warn)
                ViewShanManager.open(binding.faultView)
            }
        }
    }

    override fun ipIsInValid() {
        showSnackBar("IP地址或端口设置不符合规范")
    }

    override fun confirm() {
        "人为干预故障灯开始计时".logd(TAG)
        closeFaultViewShan = true
        if (mViewModel.bothDevicesOnline.value == true) {
            runOnUiThread {
                binding.faultView.setImageResource(R.drawable.commstatus_normal)
            }
        } else {
            runOnUiThread {
                binding.faultView.setImageResource(R.drawable.commstatus_warn)
            }
        }
        binding.faultView.visibility = View.VISIBLE
        ViewShanManager.close(binding.faultView)
        closeFaultViewShanCount = 0
    }

    override fun saveAutoHYSuccess() {
        showSnackBar("自动横移尺寸保存成功")

    }
}